<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户管理 - 虚拟仓系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    {% include 'includes/navbar.html' %}

    <div class="container mt-4">
        <h3>用户管理</h3>
        <div class="row mb-4">
            <div class="col-md-12 text-end">
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">添加用户</button>
            </div>
        </div>
        <div class="card">
            <div class="card-body">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>角色</th>
                            <th>创建时间</th>
                            <th>最后登录</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="userTable"></tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 添加用户弹窗 -->
    <div class="modal fade" id="addUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加用户</h5>
                    <button class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addUserForm">
                        <div class="mb-3">
                            <label>用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="username" required>
                        </div>
                        <div class="mb-3">
                            <label>密码 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" name="password" required>
                        </div>
                        <div class="mb-3">
                            <label>角色 <span class="text-danger">*</span></label>
                            <select class="form-select" name="role" required>
                                <option value="operator">操作员（默认）</option>
                                <option value="admin">管理员</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button id="submitAdd" class="btn btn-primary">确认添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑用户弹窗 -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑用户</h5>
                    <button class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        <input type="hidden" name="id">
                        <div class="mb-3">
                            <label>用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="username" required>
                        </div>
                        <div class="mb-3">
                            <label>密码（不填则不修改）</label>
                            <input type="password" class="form-control" name="password" placeholder="留空则保持原密码">
                        </div>
                        <div class="mb-3">
                            <label>角色 <span class="text-danger">*</span></label>
                            <select class="form-select" name="role" required>
                                <option value="operator">操作员</option>
                                <option value="admin">管理员</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button id="submitEdit" class="btn btn-primary">确认更新</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 页面加载时检查登录状态
        window.onload = async () => {
            const res = await fetch('/api/check_login');
            const data = await res.json();
            if (!data.is_login) {
                window.location.href = '/login_page';
                return;
            }
            // 检查是否为管理员
            if (data.role !== 'admin') {
                alert('无权限访问（需管理员权限）');
                window.history.back();
                return;
            }
            loadUsers();  // 加载用户列表
        };

        // 加载用户列表
        const loadUsers = async () => {
            const res = await fetch('/api/users');
            const users = await res.json();
            const table = document.getElementById('userTable');
            table.innerHTML = users.map(user => `
                <tr>
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td><span class="badge ${user.role === 'admin' ? 'bg-danger' : 'bg-primary'}">
                        ${user.role === 'admin' ? '管理员' : '操作员'}
                    </span></td>
                    <td>${user.created_at}</td>
                    <td>${user.last_login || '未登录'}</td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="editUser(${JSON.stringify(user)})">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        };

        // 编辑用户
        const editUser = (user) => {
            const form = document.getElementById('editUserForm');
            form.querySelector('input[name="id"]').value = user.id;
            form.querySelector('input[name="username"]').value = user.username;
            form.querySelector('select[name="role"]').value = user.role;
            // 清空密码框（避免显示加密密码）
            form.querySelector('input[name="password"]').value = '';
            const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
            modal.show();
        };

        // 删除用户
        const deleteUser = async (id) => {
            if (!confirm('确定要删除该用户吗？')) return;
            const res = await fetch(`/api/users/${id}`, { method: 'DELETE' });
            const data = await res.json();
            alert(data.message);
            if (data.status === 'success') loadUsers();
        };

        // 提交添加用户
        document.getElementById('submitAdd').addEventListener('click', async () => {
            const formData = Object.fromEntries(new FormData(document.getElementById('addUserForm')));
            const res = await fetch('/api/users', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });
            const data = await res.json();
            alert(data.message);
            if (data.status === 'success') {
                document.getElementById('addUserForm').reset();
                document.querySelector('#addUserModal .btn-close').click();
                loadUsers();
            }
        });

        // 提交编辑用户
        document.getElementById('submitEdit').addEventListener('click', async () => {
            const formData = Object.fromEntries(new FormData(document.getElementById('editUserForm')));
            // 密码为空则不传递（后端不更新密码）
            if (!formData.password) delete formData.password;
            const res = await fetch(`/api/users/${formData.id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });
            const data = await res.json();
            alert(data.message);
            if (data.status === 'success') {
                document.querySelector('#editUserModal .btn-close').click();
                loadUsers();
            }
        });
    </script>
</body>
</html>